import socket
import time
import os
import json
from tqdm import tqdm


f = open("./configure.json", 'r')
conf = json.load(f)
f.close()

s = socket.socket()
host = conf["host"]
port = conf["port"]

def rev_block(s):
    data = []
    while True: #循环接收
        data.append(s.recv(1)) #接收1024字节
        if data[-1][-1] == 0x00:
            break
    return b"".join(data).decode('utf-8')


def send_file_single(cmd_src, cmd_dst):
    is_send = False
    with open(cmd_src, 'rb') as f:
        file_bytes = f.read()
    len_file = len(file_bytes)
    cmd = "send_file" + " " + cmd_dst + " " + str(len_file)
    s.send((cmd + "\0").encode(encoding = "utf-8"))
    stra = rev_block(s)
    if stra[0:5] == "ready":
        is_send = True
    if is_send:
        # print(file_bytes)
        print('sending ' + cmd_src)
        for send_part in tqdm(range(len_file//2048+1)):
            if send_part!=len_file//2048:
                s.sendall(file_bytes[2048*send_part:send_part*2048+2048])
            else:
                s.sendall(file_bytes[2048*send_part:])
        # s.sendall(file_bytes)
        # print(a)
        print("sending successfully, sending bytes total:", len(file_bytes))
        stra = rev_block(s)
        print(stra)
        return True
    else:
        print('sending failed')
        return False
    
def send_file(cmd):
    cmd_list = cmd.split(' ')
    is_send = False
    if len(cmd_list)==3:
        # cmd_dict = cmd_list[0]
        cmd_src = cmd_list[1]
        cmd_dst = cmd_list[2]
    elif len(cmd_list)==2:
        cmd_src = cmd_list[1]
        if not cmd_src.endswith("*"):
            return False
    else:
        return False
    if cmd_src.endswith("*"):
        cmd_src = cmd_src[0:-2]
        if not os.path.exists(cmd_src):
            print('path not exist')
            return False
        file_list = os.listdir(cmd_src)
        for i, file_name in enumerate(file_list):
            data = send_file_single(os.path.join(cmd_src, file_name), file_name)
            if i!=len(file_list)-1:
                stra = rev_block(s)
        return True
    else:
        if not os.path.exists(cmd_src):
            print("file not exists")
            return False
        return send_file_single(cmd_src, cmd_dst)
    
if __name__=='__main__':
    s.connect((host, port))
    s.setblocking(1)
    data = rev_block(s)
    while(True):
        st = data.find('#Poki', 0, len(data))
        print(data[:st])
        cmd = input(data[st:])
        if cmd.startswith("cp"):
            if not send_file(cmd):
                s.send(("mmm\0").encode('utf-8'))
            data = rev_block(s)

        else:
            s.send((cmd + "\0").encode('utf-8'))
            data = rev_block(s)
